package it.fantacalcio.hibernate.dao;

import it.fantacalcio.model.User;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

public class UserDAOImpl extends BaseHibernateDAO implements UserDAO {

	@Override
	public void save(User user) throws Exception {
		getSession().save(user);
	}
	
	@Override
	public void delete(User user) throws Exception {
		getSession().delete(user);
	}
	@Override
	public void update(User user) throws Exception {
		getSession().saveOrUpdate(user);
	}

	@Override
	public User get(Long id) throws Exception {
		return (User) getSession().get(User.class, id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<User> list() throws Exception {
		String queryString = "from User";
		Query queryObject = getSession().createQuery(queryString);
		return queryObject.list();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<User> listaAttivi() throws Exception {
		String queryString = "from User as u where u.attivo = 'SI'";
		Query queryObject = getSession().createQuery(queryString);
		return queryObject.list();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<User> findByExample(User user) throws Exception {
		Criteria cri = getSession().createCriteria(User.class);
		cri.add(Example.create(user).ignoreCase());
		if(user.getRole()!=null){
			cri.add(Restrictions.eq("role", user.getRole()));
		}
		List<User> results = cri.list();
		return results;
	}
	
	@Override
	public User findByUsernameAndPassword(String username, String password)
			throws Exception {
		Criteria cri = getSession().createCriteria(User.class);
		cri.add(Restrictions.eq("username", username));
		cri.add(Restrictions.eq("password", password));
		cri.add(Restrictions.eq("attivo", "SI"));
		User results = (User) cri.uniqueResult();
		return results;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> listaPresidenti() throws Exception {
		String queryString = "select u from User as u where u.attivo = 'SI' and " +
								"u.id not in (select u.id from User as u, Squadra as s where s.presidente = u)";
		Query queryObject = getSession().createQuery(queryString);
		return queryObject.list();
	}

}
